/*
This file is part of lAPIn.

lAPIn is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

lAPIn is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with lAPIn.  If not, see <http://www.gnu.org/licenses/>.
*/
package org.opensource.nabaztag.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * Helper class to facilitate URL handling.
 */
public class URLUtil {


    private URLUtil() {
    }

    public static String get(final URL url, final String parameters) throws IOException {
        OutputStreamWriter writer = null;
        BufferedReader reader = null;
        try {
            final URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            writer = new OutputStreamWriter(conn.getOutputStream());

            //write parameters
            writer.write(parameters);
            writer.flush();

            // Get the response
            final StringBuilder answer = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                answer.append(line);
            }
            return answer.toString();

        } finally {
            writer.close();
            reader.close();
        }

    }

}
